package com.example.wxvoce;

import android.content.Context;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.util.Log;

import androidx.core.content.FileProvider;
import androidx.documentfile.provider.DocumentFile;

import com.example.wxvoce.bean.MusicBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {


    public static List<DocumentFile> docList = new ArrayList<>();

    //转换至uriTree的路径
    public static String changeToUri3(String path) {
        path = path.replace("/storage/emulated/0/", "").replace("/", "%2F");
        return ("content://com.android.externalstorage.documents/tree/primary%3A" + path);
    }



    //遍历文件夹
    public static DocumentFile getFiles1(DocumentFile documentFile) {
        if (documentFile.listFiles().length==0){
            return null;
        }
        Log.d("文件:", documentFile.getName());

        String md5path="";

        if (documentFile.isDirectory()) {
            for (DocumentFile file : documentFile.listFiles()) {

                if(file.getName().equals("cache")){

                    DocumentFile maxStr = file.listFiles()[0];

                    for (DocumentFile f:file.listFiles()){

                        if(f.getName().length()>maxStr.getName().length()){
                            maxStr = f;
                        }
                    }
                    //获取md5文件夹
                    md5path = maxStr.getName();

                    Log.d("TGA:", md5path);

                }

                if (file.getName().equals("MicroMsg")) {
                    for (DocumentFile d:file.listFiles()){

                        if(d.getName().equals(md5path)){
                            for (DocumentFile f:d.listFiles()){

                               // Log.d("TGA:", f.getName());

                                long maxTime = Long.MIN_VALUE;
                                DocumentFile doc = null;



                                if(f.getName().equals("voice2")){
                                    for (DocumentFile df:f.listFiles()){
                                        // Log.v("TGA",df.getName());


                                        if(df.lastModified()>maxTime){
                                            doc = df;
                                            maxTime = df.lastModified();
                                        }
                                    }

                                    if(doc!=null){
                                        Log.v("TGA最大",doc.getName());
                                        getFiles2(doc);//递归调用
                                    }
//
                                }
                            }
                        }
                    }

                }
            }

        }


        if (newestFile != null) {
            //System.out.println("TGA最新的文件是：" + newestFile.getUri());
            return  newestFile;
        }
        return null;
    }

    public static DocumentFile newestFile = null;
    public static long newestLastModified = Long.MIN_VALUE;

    public static void getFiles2(DocumentFile documentFile) {

        if (documentFile.listFiles().length==0){
            return;
        }
        //Log.d("文件:", documentFile.getName());
        if (documentFile.isDirectory()) {
            for (DocumentFile file : documentFile.listFiles()) {
                if(file.isDirectory()){
                    getFiles2(file);//递归调用
                }else {
                    if(file.getName().lastIndexOf("amr")>0){
                        //Log.v("TGA",file.getName());

                        if (file.lastModified() > newestLastModified) {
                            newestFile = file;
                            newestLastModified = file.lastModified();
                        }

                    }

                }

            }

        }
    }



    public static List<MusicBean> getFileList(){
        File file = new File("/storage/emulated/0/Download/WxVoice/WxVoice");

        if(file==null){
            return null;
        }

        List<MusicBean> musicBeanList = new ArrayList<>();
        for(File f: file.listFiles() ){
            if(f.isFile()){
                musicBeanList.add(new MusicBean(f.getName(),f.getAbsolutePath()));
            }

        }
        return musicBeanList;
    }

    //复制文件 File to DocumentFile DocumentsContract
    public static void fileToDocumentFile(Context context, File originFile, String fileName, Uri parentUri) {
        //String fileName = originFile.getName();

        Uri copyurl = parentUri;

        try {
            InputStream in = new FileInputStream(originFile);
            Uri documentFile = DocumentsContract.createDocument(context.getContentResolver(), copyurl, "*/*", fileName);
            //DocumentFile写入流
            OutputStream out = context.getContentResolver().openOutputStream(documentFile);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Uri getFileUri(Context context, File file) {
        return FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
    }

    public static void replaceMP3Content(Context context, Uri sourceUri, Uri targetUri) throws IOException {
        DocumentFile sourceFile = DocumentFile.fromSingleUri(context, sourceUri);
        DocumentFile targetFile = DocumentFile.fromSingleUri(context, targetUri);

        // 获取源文件的输入流
        InputStream inputStream = context.getContentResolver().openInputStream(sourceUri);

        // 创建目标文件的输出流
        OutputStream outputStream = context.getContentResolver().openOutputStream(targetUri);

        if (inputStream != null && outputStream != null) {
            byte[] buffer = new byte[1024];
            int length;

            while ((length = inputStream.read(buffer)) > 0) {
                // 将源文件的内容写入目标文件
                outputStream.write(buffer, 0, length);
            }

            outputStream.close();
            inputStream.close();
        }
    }


}
